package logic

import (
	"fmt"
	"github.com/gogap/logs"
	"log"
	"strconv"
	"time"
	"yundian/internel/app/dao/memberdao"
	"yundian/internel/app/helper/resphelper/placeresp"
	"yundian/internel/app/models/membermodel"
	"yundian/internel/app/models/placemodel"

	"yundian/internel/app/dao"
	"yundian/internel/app/helper"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/models/orders"
	"yundian/internel/app/models/ordersmonthly"
	"yundian/internel/app/models/users"
	"yundian/internel/pkg/dbs"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/dingo/global"
	"yundian/internel/pkg/utils"
)

type OrderListUseType struct {
	orders.OrderModel
	BranchUserId int    `gorm:"column:branch_user_id"`
	EndDate      string `gorm:"column:end_date"`
	EndMonth     string `gorm:"column:end_month"`
}

// 是否正在恢复错误订单
var RecoverOrderOff struct {
	Off  bool
	time int64
}

// 分红表同步结算时间 每天晚上 12:05 执行
func (task *TaskLogic) OrderDividendsSyncEndAt() {
	sql := `UPDATE dividends_log dl LEFT JOIN orders o ON dl.trade_no = o.trade_no SET dl.create_at=o.end_at,dl.end_date=
	DATE_FORMAT(FROM_UNIXTIME(o.end_at), '%Y-%m-%d'),dl.end_month=DATE_FORMAT(FROM_UNIXTIME(o.end_at), '%Y-%m')
	WHERE dl.create_at<>o.end_at AND o.trade_no>'ZM20210701'`
	if db := global.Orm.Exec(sql); db.Error != nil {
		log.Println("OrderDividendsSyncEndAt-err", db.Error)
		return
	}
}

// 删除异常分红 每天晚上 12:10 执行
func (task *TaskLogic) OrderDividendsDeleteError() {
	updateSql := `UPDATE dividends_log dl LEFT JOIN  orders o ON o.trade_no=dl.trade_no 
	SET dl.state=-1  WHERE dl.user_id>0 AND o.state<>?`
	if db := global.Orm.Exec(updateSql, helper.TypeNumOrderStatusFinish); db.Error != nil {
		log.Println("OrderDividendsDeleteError-UPDATE-err", db.Error)
		return
	}

	deleteSql := `DELETE FROM dividends_log WHERE user_id=0 OR state=-1`
	if db := global.Orm.Exec(deleteSql); db.Error != nil {
		log.Println("OrderDividendsDeleteError-DELETE-err", db.Error)
		return
	}
}

// 订单关联表异常恢复 每天晚上 12:15 执行
func (task *TaskLogic) OrderRelevanceSyncRecover(startTime, endTime string, max int) {
	//d, _ := time.ParseDuration("-24h")
	//startTime := time.Now().Add(d * dayLen).Format("2006-01-02 15:04:05")
	//endTime := time.Now().Format("2006-01-02 15:04:05")
	days := utils.CreateDays(startTime, endTime, "20060102150405", 8)

	var tradeNoList []string
	//var tradeNoExistList []string
	var orderListUse []OrderListUseType
	var orderListUseInsert []OrderListUseType

	sql := `SELECT o.*,p.branch_user_id,DATE_FORMAT(FROM_UNIXTIME(o.end_at), '%Y-%m-%d')end_date,DATE_FORMAT
	(FROM_UNIXTIME(o.end_at), '%Y-%m')end_month FROM (SELECT * FROM orders WHERE trade_no>=? AND trade_no<=?) o 
	LEFT JOIN places p ON o.place_id=p.id LEFT JOIN (SELECT trade_no FROM orders_user_relevancy WHERE trade_no>=? 
	AND trade_no<=? GROUP BY trade_no) our ON o.trade_no=our.trade_no WHERE our.trade_no IS NULL`
	for index, dayTime := range days {
		if index != len(days)-1 {
			var targetList []OrderListUseType
			sh, _ := time.ParseDuration("-1s")
			eh, _ := time.ParseDuration("1s")
			st, _ := time.ParseInLocation("20060102150405", dayTime, time.Local)
			et, _ := time.ParseInLocation("20060102150405", days[index+1], time.Local)
			startSql := fmt.Sprintf("ZM%s", st.Add(sh).Format("20060102150405"))
			endSql := fmt.Sprintf("ZM%s", et.Add(eh).Format("20060102150405"))
			if db := global.Orm.Raw(sql, startSql, endSql, startSql, endSql).Find(&targetList); db.Error != nil {
				logs.Error("OrderRelevanceSyncRecover-err", db.Error)
			}
			orderListUse = append(orderListUse, targetList...)
		}
	}

	for _, item := range orderListUse {
		tradeNoList = append(tradeNoList, item.TradeNo)
	}
	if len(tradeNoList) == 0 {
		RecoverOrderOff.Off = false
		return
	}

	// 同步分红表到订单关联表
	//insertSql := `INSERT INTO orders_user_relevancy (user_id, trade_no,end_date,end_month) SELECT dl.user_id,dl.trade_no,
	//DATE_FORMAT(FROM_UNIXTIME(o.end_at), '%Y-%m-%d') end_date,DATE_FORMAT(FROM_UNIXTIME(o.end_at), '%Y-%m') end_month
	//FROM dividends_log dl LEFT JOIN orders o ON o.trade_no=dl.trade_no WHERE dl.user_id>0 AND o.state=5 AND
	//dl.trade_no IN (?) GROUP BY user_id, trade_no`
	//if db := global.Orm.Exec(insertSql, tradeNoList); db.Error != nil {
	//	logs.Error("OrderRelevanceSyncRecover-insert-err", db.Error)
	//}
	//
	//db := global.Orm.Table("dividends_log dl").Select("DISTINCT dl.trade_no")
	//if db.Where("dl.trade_no IN (?)", tradeNoList).Find(&tradeNoExistList); db.Error != nil {
	//	logs.Error("OrderRelevanceSyncRecover-tradeNoExistList-err", db.Error)
	//}

	m := map[string]bool{}
	for _, item := range orderListUse {
		if !m[item.TradeNo] {
			orderListUseInsert = append(orderListUseInsert, item)
		}
		m[item.TradeNo] = true
	}

	task.OrderRelevanceSyncDataExec(orderListUseInsert, max)
}

// 订单关联表自动同步 每10秒同步一次
func (task *TaskLogic) OrderRelevanceSyncData() {
	maxOrderId := int64(0)
	var orderListUse []OrderListUseType

	maxOrderIdSql := `SELECT id FROM orders_user_relevancy ORDER BY id DESC LIMIT 1`
	if db := global.Orm.Raw(maxOrderIdSql).Find(&maxOrderId); db.Error != nil {
		logs.Error("maxOrderId-err", db.Error)
		return
	}

	orderSql := `SELECT o.*,p.branch_user_id,DATE_FORMAT(FROM_UNIXTIME(o.end_at), '%Y-%m-%d')end_date,DATE_FORMAT(
	FROM_UNIXTIME(o.end_at), '%Y-%m')end_month FROM orders o LEFT JOIN places p ON o.place_id=p.id WHERE o.id>? 
	ORDER BY o.id limit 500 OFFSET 0`
	if db := global.Orm.Raw(orderSql, maxOrderId).Find(&orderListUse); db.Error != nil {
		logs.Error(db.Error)
		return
	}

	task.OrderRelevanceSyncDataExec(orderListUse, 300)
}

// 订单关联表结算日期同步
func (task *TaskLogic) OrderRelevanceSyncDate() {
	if RecoverOrderOff.Off && (time.Now().Unix()-RecoverOrderOff.time) < 300 {
		logs.Error("OrderRelevanceSyncDate-err->正在恢复错误订单")
		RecoverOrderOff.Off = false
		return
	}

	var tradeNoList []string
	maxDay := time.Duration(60)
	if time.Now().Minute() > 15 {
		maxDay = 15
	}
	d, _ := time.ParseDuration("-24h")
	maxTradeNo := fmt.Sprintf("ZM%s", time.Now().Add(maxDay*d).Format("20060102"))

	maxTradeNoSql := `SELECT o.trade_no FROM orders_user_relevancy our LEFT JOIN orders o ON our.trade_no = o.trade_no
	WHERE DATE_FORMAT(FROM_UNIXTIME(o.end_at), '%Y-%m-%d')<>our.end_date AND our.trade_no>=? AND o.end_at>0 LIMIT 5000`
	if db := global.Orm.Raw(maxTradeNoSql, maxTradeNo).First(&tradeNoList); db.Error != nil {
		logs.Error("maxTradeNoSql-err", db.Error)
		return
	}

	updateSql := `UPDATE orders_user_relevancy our LEFT JOIN orders o ON our.trade_no = o.trade_no SET our.end_date=
	DATE_FORMAT(FROM_UNIXTIME(o.end_at), '%Y-%m-%d'),our.end_month=DATE_FORMAT(FROM_UNIXTIME(o.end_at), '%Y-%m')
	WHERE our.trade_no IN (?) AND o.end_at>0`
	if db := global.Orm.Debug().Exec(updateSql, tradeNoList); db.Error != nil {
		log.Println("OrderRelevanceSyncDate-UPDATE-err", db.Error)
		return
	}
}

// 订单关联执行，非分红表
func (task *TaskLogic) OrderRelevanceSyncDataExec(orderListUse []OrderListUseType, max int) {
	if len(orderListUse) == 0 {
		return
	}

	userMap := map[int][]int{}
	insertList := []map[string]interface{}{}
	for index, item := range orderListUse {
		if userMap[item.UserId] == nil {
			list := dao.NewUserDao().QueryParentList(item.UserId, item.BranchUserId).Unwrap().([]*users.UserModel)
			userMap[item.UserId] = toRepetition(list)
		}
		for _, userId := range userMap[item.UserId] {
			insertList = append(insertList, map[string]interface{}{
				"user_id":   userId,
				"id":        item.Id,
				"trade_no":  item.TradeNo,
				"end_date":  item.EndDate,
				"end_month": item.EndMonth,
			})
		}

		if len(insertList) >= max || index == len(orderListUse)-1 {
			if db := global.Orm.Table("orders_user_relevancy").Create(insertList); db.Error != nil {
				log.Println("orders_user_relevancy ERR", db.Error, item)
				if RecoverOrderOff.Off {
					logs.Error("OrderRelevanceSyncDataExec-err->正在恢复错误订单")
					return
				}
				logs.Error("OrderRelevanceSyncDataExec-Exec->正在恢复错误订单")
				RecoverOrderOff.Off = true
				RecoverOrderOff.time = time.Now().Unix()
				h5, _ := time.ParseDuration("-120h")
				startTime := time.Now().Add(h5).Format("2006-01-02 15:04:05")
				endTime := time.Now().Format("2006-01-02 15:04:05")
				task.OrderRelevanceSyncRecover(startTime, endTime, 1)

				if max > 1 {
					return
				}
			}
			insertList = insertList[:0]
			log.Println("成功", item)
		}
	}
	RecoverOrderOff.Off = false
}

func toRepetition(list []*users.UserModel) []int {
	var newList []int
	for _, item := range list {
		off := true
		for _, id1 := range newList {
			if item.ID == id1 {
				off = false
				break
			}
		}
		if off {
			newList = append(newList, item.ID)
		}
	}
	return newList
}

//查询是否存在通知失败的，存在则再次通知
func QueryNotificationFailSync() {
	var m []placemodel.PlacesServiceNotification
	global.Orm.Table("places_service_notification").Where("status = 2").Find(&m)
	if len(m) > 0 {

		for _, v := range m {
			//查询员工信息
			placesStaffOpenIds := dao.NewNotificationDaoDao().GetStaffOpenIdByPlaceId(v.PlaceId, v.NotificationType).Unwrap().([]placeresp.StaffBasicInfo)
			//查询网点通知方式
			placesConfigInfo := dao.NewNotificationDaoDao().GetPlacesNotificationConfig(v.PlaceId).Unwrap().(*placemodel.PlacesInformationConfig)

			////修改状态
			//serviceNotificationModel := &placemodel.PlacesServiceNotification{}
			//serviceNotificationModel.Id = v.Id
			//serviceNotificationModel.Status = 4
			//dao.NewNotificationDaoDao().UpdatePlaceServiceNotification(serviceNotificationModel)

			switch placesConfigInfo.Type {

			case 1:
				//钉钉群机器人异步调用通知
				dingo.Task(NewShWxNotificationsLogic().DingTalkGroupRobotNotifications, func() {}, v, placesStaffOpenIds, placesConfigInfo)
			case 2:
				//企业微信群机器人异步调用通知
				dingo.Task(NewShWxNotificationsLogic().WeChatGroupRobotNotifications, func() {}, v, placesStaffOpenIds, placesConfigInfo)
			case 3:
				//钉钉异步调用通知
				dingo.Task(NewShWxNotificationsLogic().DingTalkNotificationsData, func() {}, v, placesStaffOpenIds, placesConfigInfo)
			case 4:
				//微信企业异步调用通知
				dingo.Task(NewShWxNotificationsLogic().WeChatGroupNotificationsData, func() {}, v, placesStaffOpenIds, placesConfigInfo)
			case 5:
				//公众号异步调用通知
				dingo.Task(NewShWxNotificationsLogic().WeChatPublicNotificationsData, func() {}, v, placesStaffOpenIds, placesConfigInfo)
			}
		}

	}

}

// 客房超市自动取消订单
func (task *TaskLogic) GoodsAutoCancelOrder() {
	orderIds := []int{}
	goodsMap := map[int]int{}
	updateMap := map[int][]int{}
	orderList, err := dao.NewGoodsDao().GetGoodsOrdersByStatus(helper.TypeNumGoodsOrderStatusWait)
	if err != nil {
		logs.Error("GetGoodsOrdersByStatus-err", err)
		return
	}

	for _, item := range orderList {
		orderIds = append(orderIds, item.Id)
		if goodsMap[item.GoodsId] > 0 {
			goodsMap[item.GoodsId] += item.BuyNum
		} else {
			goodsMap[item.GoodsId] = item.BuyNum
		}
	}

	for goodsId, buyNum := range goodsMap {
		if len(updateMap[buyNum]) > 0 {
			updateMap[buyNum] = append(updateMap[buyNum], goodsId)
		} else {
			updateMap[buyNum] = []int{goodsId}
		}
	}

	if len(updateMap) == 0 {
		return
	}

	tx, key := dbs.GormBegin("GoodsAutoCancelOrder")
	updateSql := `UPDATE goods SET sell_num=sell_num-?,num=num+? WHERE id IN ?`
	for buyNum, goodsIds := range updateMap {
		if db := tx.Exec(updateSql, buyNum, buyNum, goodsIds); db.Error != nil {
			dbs.GormRollback(tx, key, db.Error)
			return
		}
	}
	if db := tx.Exec(`UPDATE goods_orders SET status=? WHERE id IN ?`, helper.TypeNumGoodsOrderStatusCancel, orderIds); db.Error != nil {
		dbs.GormRollback(tx, key, db.Error)
		return
	}
	dbs.GormCommit(tx, key)
	logs.Info("客房超市自动取消订单-完成", orderIds)
}

// 获取门店 上月流水、本月流水 保存至缓存表
//func (task *TaskLogic) GetPlaceTotalSettlement()  {
//	global.Orm.Debug().Exec("delete from last_settlement_cache")
//
//	beginTimeLast, endTimeLast := wechatpay.GetLastMonthStartEnd()
//	global.Orm.Debug().Exec("INSERT INTO last_settlement_cache SELECT p.id as place_id,IFNULL(a.settlement_money,0) as settlement_money,IFNULL(a.m,DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m')) as m FROM places p LEFT JOIN (SELECT SUM(settlement_money) as settlement_money,place_id,DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m') as m FROM orders " +
//		"WHERE is_draw = 0 and state = 5 and end_at >= ? and end_at <= ? GROUP BY place_id) a ON p.id = a.place_id;", beginTimeLast, beginTimeLast, endTimeLast)
//
//	beginTimeNow, endTimeNow := wechatpay.GetNowMonthStartEnd()
//	global.Orm.Debug().Exec("INSERT INTO last_settlement_cache SELECT p.id as place_id,IFNULL(a.settlement_money,0) as settlement_money,IFNULL(a.m,DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m')) as m FROM places p LEFT JOIN (SELECT SUM(settlement_money) as settlement_money,place_id,DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m') as m FROM orders " +
//		"WHERE is_draw = 0 and state = 5 and end_at >= ? and end_at <= ? GROUP BY place_id) a ON p.id = a.place_id;", beginTimeNow, beginTimeNow, endTimeNow)
//}

// 上月订单缓存表 - 一天更新一次
func (task *TaskLogic) GetOrderCacheByMonth(beginTime, endTime int64, t string) {
	global.Orm.Exec("DROP TABLE IF EXISTS " + t + ";")
	global.Orm.Exec("CREATE TABLE " + t + " LIKE orders;")
	global.Orm.Exec("INSERT INTO "+t+" SELECT * FROM `orders` WHERE end_at >= ? and end_at <= ?", beginTime, endTime)
}

func (task *TaskLogic) AutoTradePayByMonthOld() {
	orderList := dao.NewOrderAutoRenewDao().GetAutoRenewMonthlyAwaitList().Unwrap().([]*request.GetAutoRenewMonthlyAwaitListReq)
	for _, item := range orderList {
		// 查询此签约号下的 1元订单如果撤销了，则不扣款
		oInfo,_ := dao.NewOrderAutoRenewDao().GetAutoOrderByAgreementNo(item.AgreementNo)
		if oInfo.Status == 6 && oInfo.RenewStatus == 4 {
			param := &request.AliPayAutoTradeCreate{
				AgreementNo: item.AgreementNo, // 签约号
				Openid:      item.Openid,      // 用户ID
				Money:       9900,             // 单位分
			}
			aliPayOrderLogic := NewAliPayOrderLogicAppid(item.AppId, "")
			respData, err := aliPayOrderLogic.AliPayAutoTradeCreate(param)

			if respData.Response.SubCode == "ACQ.AGREEMENT_NOT_EXIST" {
				dao.NewOrderAutoRenewDao().UpdateAutoRenewMonthlyByAgreementClose(item.Id)
				continue
			}

			// 扣款日期不在签约时的允许范围之内
			if respData.Response.SubCode == "ACQ.CYCLE_PAY_DATE_NOT_MATCH" {
				h, _ := time.ParseDuration("24h")
				param.RenewTime = time.Now().Add(h).Format("2006-01-02")
				respModifyData, err := aliPayOrderLogic.AliPayAutoExecModify(param)
				if respModifyData.Response.Code == "10000" {
					dao.NewOrderAutoRenewDao().UpdateAutoRenewMonthlyPay(&ordersmonthly.OrderMonthlyModel{
						OrderMonthlyDB: ordersmonthly.OrderMonthlyDB{TradeNo: item.TradeNo},
						RenewTime:      param.RenewTime,
					})
				}
				fmt.Println("AliPayAutoExecModify-ERR", respModifyData.Response.Msg, err)
				continue
			}

			if respData.Response.Code != "10000" || err != nil {
				fmt.Println("AutoTradePayByMonth-ERR", respData.Response.Code, respData.Response.Msg, err)
				fmt.Println("AutoTradePayByMonth-ERR", item.AppId, aliPayOrderLogic.TradeNo)
				continue
			}

			// 创建支付订单
			toRenewTime := utils.IfTrueString(item.UpdateRenewTime != "1970-01-01 00:00:00", item.UpdateRenewTime, item.RenewTime)
			tNow, _ := time.Parse("2006-01-02 15:04:05", toRenewTime)
			day, _ := strconv.Atoi(global.Cfg.Ali.AutoPayDay)
			h, _ := time.ParseDuration(fmt.Sprintf("%dh", 24*day))
			renewTime := tNow.Add(h).Format("2006-01-02 15:04:05")
			if item.PeriodType == 2 {
				renewTime = utils.AddDate(tNow, 0, 1).Format("2006-01-02 15:04:05")
			}
			dbParam := &request.AliPayUserAgreementSignRes{
				Money:       param.Money,
				UserId:      item.MemberId,
				AgreementNo: item.AgreementNo,
				RenewTime:   renewTime,
				PeriodType:  item.PeriodType,
			}
			if data := dao.NewOrderAutoRenewDao().CreateAutoRenewMonthlyType(dbParam, aliPayOrderLogic.TradeNo); data.Err != nil {
				fmt.Println("AutoTradePayByMonth", data.Err)
			}
			fmt.Println("AutoTradePayByMonth-INFO", respData, err)
		}
	}
}

// 周期扣款 月会员续费
func (task *TaskLogic) AutoTradePayByMonth() {
	orderList := dao.NewOrderAutoRenewDao().GetAutoRenewMonthlyAwaitList().Unwrap().([]*request.GetAutoRenewMonthlyAwaitListReq)
	for _, item := range orderList {
		// 查询此签约号下的 1元订单如果撤销了，则不扣款
		oInfo,_ := dao.NewOrderAutoRenewDao().GetAutoOrderByAgreementNo(item.AgreementNo)
		price, _ := strconv.Atoi(global.Cfg.Ali.AutoPayPrice)
		if oInfo.Status != 6 && oInfo.RenewStatus != 4 {
			param := &request.AliPayAutoTradeCreate{
				AgreementNo: item.AgreementNo, // 签约号
				Openid:      item.Openid,      // 用户ID
				Money:       int64(price*100),             // 单位分
			}
			aliPayOrderLogic := NewAliPayOrderLogicAppid(item.AppId, "")
			respData, err := aliPayOrderLogic.AliPayAutoTradeCreate(param)

			if respData.Response.SubCode == "ACQ.AGREEMENT_NOT_EXIST" {
				dao.NewOrderAutoRenewDao().UpdateAutoRenewMonthlyByAgreementClose(item.Id)
				continue
			}

			// 扣款日期不在签约时的允许范围之内
			if respData.Response.SubCode == "ACQ.CYCLE_PAY_DATE_NOT_MATCH" {
				h, _ := time.ParseDuration("24h")
				param.RenewTime = time.Now().Add(h).Format("2006-01-02")
				respModifyData, err := aliPayOrderLogic.AliPayAutoExecModify(param)
				if respModifyData.Response.Code == "10000" {
					dao.NewOrderAutoRenewDao().UpdateAutoRenewMonthlyPay(&ordersmonthly.OrderMonthlyModel{
						OrderMonthlyDB: ordersmonthly.OrderMonthlyDB{TradeNo: item.TradeNo},
						RenewTime:      param.RenewTime,
					})
				}
				fmt.Println("AliPayAutoExecModify-ERR", respModifyData.Response.Msg, err)
				continue
			}

			if respData.Response.Code != "10000" || err != nil {
				fmt.Println("AutoTradePayByMonth-ERR", respData.Response.Code, respData.Response.Msg, err)
				fmt.Println("AutoTradePayByMonth-ERR", item.AppId, aliPayOrderLogic.TradeNo)
				continue
			}

			// 创建支付订单
			toRenewTime := utils.IfTrueString(item.UpdateRenewTime != "1970-01-01 00:00:00", item.UpdateRenewTime, item.RenewTime)
			tNow, _ := time.Parse("2006-01-02 15:04:05", toRenewTime)
			day, _ := strconv.Atoi(global.Cfg.Ali.AutoPayDay)
			h, _ := time.ParseDuration(fmt.Sprintf("%dh", 24*day))
			renewTime := tNow.Add(h).Format("2006-01-02 15:04:05")
			if item.PeriodType == 2 {
				renewTime = utils.AddDate(tNow, 0, 1).Format("2006-01-02 15:04:05")
			}
			dbParam := &request.AliPayUserAgreementSignRes{
				Money:       param.Money,
				UserId:      item.MemberId,
				AgreementNo: item.AgreementNo,
				RenewTime:   renewTime,
				PeriodType:  item.PeriodType,
			}
			if data := dao.NewOrderAutoRenewDao().CreateAutoRenewMonthlyType(dbParam, aliPayOrderLogic.TradeNo); data.Err != nil {
				fmt.Println("AutoTradePayByMonth", data.Err)
			}
			fmt.Println("AutoTradePayByMonth-INFO", respData, err)
		}
	}
}

// 周期扣款 月会员续费
func (task *TaskLogic) AutoTradePayByMonthByAppid(appid string) {
	orderList := dao.NewOrderAutoRenewDao().GetAutoRenewMonthlyAwaitListByAppId(appid).Unwrap().([]*request.GetAutoRenewMonthlyAwaitListReq)
	for _, item := range orderList {
		oInfo,_ := dao.NewOrderAutoRenewDao().GetAutoOrderByAgreementNoOrderByCreateTime(item.AgreementNo)
		price, _ := strconv.Atoi(global.Cfg.Ali.AutoPayPrice)
		if oInfo.Status != 6 && oInfo.RenewStatus != 4 {
			param := &request.AliPayAutoTradeCreate{
				AgreementNo: item.AgreementNo, // 签约号
				Openid:      item.Openid,      // 用户ID
				Money:       int64(price*100), // 单位分
			}
			aliPayOrderLogic := NewAliPayOrderLogicAppid(item.AppId, "")
			respData, err := aliPayOrderLogic.AliPayAutoTradeCreate(param)

			if respData.Response.SubCode == "ACQ.AGREEMENT_NOT_EXIST" {
				dao.NewOrderAutoRenewDao().UpdateAutoRenewMonthlyByAgreementClose(item.Id)
				continue
			}

			// 扣款日期不在签约时的允许范围之内
			if respData.Response.SubCode == "ACQ.CYCLE_PAY_DATE_NOT_MATCH" {
				h, _ := time.ParseDuration("24h")
				param.RenewTime = time.Now().Add(h).Format("2006-01-02")
				respModifyData, err := aliPayOrderLogic.AliPayAutoExecModify(param)
				if respModifyData.Response.Code == "10000" {
					dao.NewOrderAutoRenewDao().UpdateAutoRenewMonthlyPay(&ordersmonthly.OrderMonthlyModel{
						OrderMonthlyDB: ordersmonthly.OrderMonthlyDB{TradeNo: item.TradeNo},
						RenewTime:      param.RenewTime,
					})
				}
				fmt.Println("AliPayAutoExecModify-ERR", respModifyData.Response.Msg, err)
				continue
			}

			if respData.Response.Code != "10000" || err != nil {
				fmt.Println("AutoTradePayByMonth-ERR", respData.Response.Code, respData.Response.Msg, err)
				fmt.Println("AutoTradePayByMonth-ERR", item.AppId, aliPayOrderLogic.TradeNo)
				continue
			}

			// 创建支付订单
			toRenewTime := utils.IfTrueString(item.UpdateRenewTime != "1970-01-01 00:00:00", item.UpdateRenewTime, item.RenewTime)
			tNow, _ := time.Parse("2006-01-02 15:04:05", toRenewTime)
			day, _ := strconv.Atoi(global.Cfg.Ali.AutoPayDay)
			h, _ := time.ParseDuration(fmt.Sprintf("%dh", 24*day))
			renewTime := tNow.Add(h).Format("2006-01-02 15:04:05")
			if item.PeriodType == 2 {
				renewTime = utils.AddDate(tNow, 0, 1).Format("2006-01-02 15:04:05")
			}
			dbParam := &request.AliPayUserAgreementSignRes{
				Money:       param.Money,
				UserId:      item.MemberId,
				AgreementNo: item.AgreementNo,
				RenewTime:   renewTime,
				PeriodType:  item.PeriodType,
			}
			if data := dao.NewOrderAutoRenewDao().CreateAutoRenewMonthlyType(dbParam, aliPayOrderLogic.TradeNo); data.Err != nil {
				fmt.Println("AutoTradePayByMonth", data.Err)
			}
			fmt.Println("AutoTradePayByMonth-INFO", respData, err)
		}
	}
}

// 个人代扣协议查询
func (task *TaskLogic) AlipayUserAgreementNoQuery(tradeNo string)  {
	orderInfo, _ := dao.NewOrderAutoRenewDao().GetAutoOrderByTradeNo(tradeNo)
	logs.Info("tradeNo, memberId", tradeNo, orderInfo.MemberId)
	if orderInfo != nil && orderInfo.MemberId > 0 {
		memberInfo := memberdao.NewMemberDao().GetMemberInfoById(orderInfo.MemberId).Unwrap().(*membermodel.MembersModel)
		logs.Info("alipayUserId, appId", memberInfo.XcxOpenid, memberInfo.AppId)
		if memberInfo.XcxOpenid != "" {
			aliPayOrderLogic := NewAliPayOrderLogicAppid(memberInfo.AppId, "")

			agreementNo, status := aliPayOrderLogic.AliPayNoAgreementNoOrderQuery(memberInfo.XcxOpenid, tradeNo)
			logs.Info("agreementNo, status", agreementNo, status)
			if status == "NORMAL" { // 正常
				// 更新订单信息  5 1 agreement_no
			}
			if status == "TEMP" { // 协议未生效过也就是未开通

			}
			if status == "STOP" { // 协议已暂停

			}
		}
	}
}